<!-- 违章费用 -->
<template>
  <div class="page-container">
    <div class="quick-search">
      <div
        v-for="item in quickSearchData"
        :key="item.key"
        class="quick-search-item"
        :class="[item.checked ? 'quick-search-item-checked' : '']"
        @click="quickSearchClick(item)"
      >
        <div class="quick-search-item-label">{{ item.label }}</div>
        <div class="quick-search-item-value" :class="[item.checked ? 'quick-search-item-value-checked' : '']">{{ item.value }} 元</div>
      </div>
    </div>
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="onSearch" @reset="searcherChange" />

    <table-index
      :table="tableCompulsory"
      @loadData="loadData"
      @selection-change="selectionChange"
      @pagenationChange="pagenationChange"
      :row-class="getRowClassName"
    >
      <!-- <template #selectkey="{ record }">
        <div class="check-box"
          ><a-checkbox
            :disabled="record.feeStatus != 0 && record.feeStatus != 5"
            :value="record.id"
            @change="checkboxChange($event, record.id)"
            v-if="record.level == 1"
        /></div>
      </template> -->
      <template #expand-icon="{ expanded }">
        <icon-plus-circle style="font-size: 20px; color: #0256ff" v-if="!expanded" />
        <icon-minus-circle style="font-size: 20px; color: #0256ff" v-else />
      </template>
      <template #carmsg="{ record }">
        <template v-if="record.carLicenseNo || record.carModelName">
          <div>{{ record.carLicenseNo || '-' }}</div>
          <div>{{ record.carModel || '-' }}</div>
        </template>
        <template v-else> - </template>
      </template>
      <template #undermsg="{ record }">
        <template v-if="record.undertaker || record.undertakerTel">
          <div>{{ record.undertaker || '-' }}</div>
          <div>{{ record.undertakerTel || '-' }}</div>
        </template>
        <template v-else> - </template>
      </template>
      <template #orderCode="{ record }">
        <template v-if="record.orderCode || record.staffName">
          <div>
            <span @click="toOrderDetail(record.eventType, record.orderId, record.orderCode)" v-if="record.orderCode" class="order-line">
              {{ record.orderCode }}
            </span>
            <span v-else>-</span>
          </div>
          <div>交车人：{{ record.staffName || '-' }}</div>
        </template>
        <template v-else> - </template>
      </template>
      <template #time="{ record }">
        <template v-if="record.startTime || record.endTime">
          <div>{{ record.startTime || '-' }}</div>
          <div>{{ record.endTime || '-' }}</div>
        </template>
        <template v-else> - </template>
      </template>
      <!-- 收支方式 -->
      <template #payType="{ record }">
        <div
          >{{ record.payTypeName }}
          <a-tooltip v-if="record.payType == 4 && record.feeNameId == 55 && record.depositDeductionWay">
            <template #content>
              <div v-if="record.depositDeductionWay == 2">
                <div>违章押金>=违章费时，自动生成1条费用，支持操作</div>
              </div>
              <div v-else>
                <div>违章押金 {{ text1 }} 违章费时，自动生成两条费用</div>
                <div>费用1：押金抵扣费用，不支持操作</div>
                <div>押金2：剩余需要支付的违章费，支持操作，操作结果同步费用1</div>
              </div>
            </template>
            <icon-exclamation-circle style="font-size: 16px; color: #165dff; vertical-align: middle" />
          </a-tooltip>
        </div>
      </template>
    </table-index>
  </div>
  <fee ref="feepage" @feepageConfirm="feepageConfirm" />
  <violationEditFeeModal ref="violationEditFee" @feepageConfirm="feepageConfirm" />
  <qcode-modal
    v-model:visible="payQCodeModal"
    :details="clickRecord"
    @close="payQCodeClose"
    :qcodeTitle="qcodeTitle"
    :qcodeCfLoading="qcodeCfLoading"
    @confirm="qcodeConfirm"
    :from="qrcodeFrom"
  />
</template>

<script setup lang="ts" name="ViolationFee">
  import qcodeModal from '@/views/confirmFee/modals/qcode-modal.vue'
  import violationEditFeeModal from '@/views/editFee/violation/index.vue'
  import { reactive, onMounted, computed, ref, nextTick } from 'vue'
  import { useTable } from '@/hooks/table'
  import { useExport } from '@/hooks/list'
  import { getViolationFeeList, violationExportExcel, violationFeeMonthCount } from '@/api/finance/costConfirm.js'
  import useNavigate from '@/hooks/useNavigate'
  import { usePageDict } from '@/hooks/useDict'
  import dayjs from 'dayjs'
  import fee from '@/views/confirmFee/violation/index.vue'
  import { Message } from '@arco-design/web-vue'
  import { cancelPay } from '@/api/common'
  import { useRoute } from 'vue-router'
  import { evalQueryParam } from '@/utils'
  const route = useRoute()
  const routeQuery = route.query

  const dict = usePageDict('carviolationDict')

  const queryParam = reactive<any>({
    pageNumber: 1,
    pageSize: 10,
    feeStatuses: [0, 3, 5],
  })
  const qrcodeFrom = ref('')
  const qcodeCfLoading = ref(false)
  const qcodeTitle = ref('收款码')
  const payQCodeModal = ref(false)
  const clickRecord = ref()
  const violationEditFee = ref()
  const feepage = ref()
  const { navigateTo } = useNavigate()
  const quickSearchData = ref([
    {
      key: 1,
      label: '本月违章总额',
      value: 0,
      checked: false,
    },
    {
      key: 2,
      label: '待收款费用',
      value: 0,
      checked: false,
    },
    {
      key: 3,
      label: '待付款费用',
      value: 0,
      checked: false,
    },
  ])
  const searchList = computed(() => {
    return [
      {
        label: '车牌号',
        prop: 'licenseNoLike',
        type: 'a-input',
      },
      {
        label: '违章单关联门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_site_listBystaff',
          params: {
            oldIdList: oldIdList.value,
          },
        },
      },
      {
        label: '费用状态',
        prop: 'feeStatuses',
        type: 'a-select',
        options: dict.feeStatus,
        attrs: {
          multiple: true,
        },
      },
      { label: '违章单号', prop: 'businesCode', type: 'a-input' },
      {
        label: '负责人',
        prop: 'undertakerIdsList',
        type: 'remote-select',
        attrs: {
          mode: 'multiple',
          type: 'store_staff_list_multiple',
        },
      },
      {
        label: '应结时间',
        prop: 'dueDate',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.dueStartDate = value[0]
          queryParam.dueEndDate = value[1]
        },
      },
      {
        label: '违章时间',
        prop: 'dateRange',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.startTime = value[0]
          queryParam.endTime = value[1]
        },
      },
      {
        label: '收付款时间',
        prop: 'date',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:59:59'],
          },
        },
        change: (value = []) => {
          queryParam.payTimeStart = value[0]
          queryParam.payTimeEnd = value[1]
        },
      },
      {
        label: '客户名称',
        prop: 'customerNameLike',
        type: 'a-input',
      },
    ]
  })

  // 筛选发生变化时，清除统计样式
  const searcherChange = () => {
    quickSearchData.value.forEach((i) => {
      i.checked = false
    })
  }

  // 选择 keys
  const selectedRowKeys = ref<any[]>([])
  const checkboxChange = (e: any, id: any) => {
    const index = selectedRowKeys.value.indexOf(id)
    if (index > -1) {
      selectedRowKeys.value.splice(index, 1)
    } else {
      selectedRowKeys.value.push(id)
    }
  }
  // 页数选择后清空 复选框
  const pagenationChange = () => {
    selectedRowKeys.value = []
  }
  const selectionChange = (e: any) => {
    selectedRowKeys.value = e
  }
  const handleBatchConfirm = () => {
    if (selectedRowKeys.value.length) {
      console.log(selectedRowKeys.value)
    } else {
      Message.warning('请先勾选需要确认的数据！')
    }
  }
  //快捷查询
  const quickSearchClick = (item: any) => {
    queryParam.dateRange = []
    queryParam.startTime = undefined
    queryParam.endTime = undefined
    queryParam.feeStatuses = []
    quickSearchData.value.forEach((ele) => {
      if (ele.key == item.key) {
        ele.checked = true
      } else {
        ele.checked = false
      }
    })
    if (item.key == 1) {
      let startTime = dayjs().startOf('month').format('YYYY-MM-DD')
      let endTime = dayjs().endOf('month').format('YYYY-MM-DD')
      queryParam.dateRange[0] = startTime
      queryParam.dateRange[1] = endTime
      queryParam.startTime = startTime
      queryParam.endTime = endTime
      queryParam.costType = undefined
    }
    if (item.key == 2) {
      queryParam.feeStatuses = [3, 5]
      queryParam.costType = 0
    }
    if (item.key == 3) {
      queryParam.feeStatuses = [0, 5]
      queryParam.costType = 1
    }

    loadData()
  }
  const tableCompulsory = useTable({
    pagination: {
      page: 1,
      pageSize: 10,
      showSizePicker: false,
      pageCount: 1,
    },
    columns: [
      // , slotName: 'contractSignDate'
      // { title: ' ', slotName: 'selectkey', width: 90, fixed: 'left' },
      { title: '费用名称', dataIndex: 'feeName', fixed: 'left', width: 150 },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 100 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 100 },
      { title: '费用金额', dataIndex: 'totalAmount', unit: '元', width: 110 },
      { title: '待结金额', dataIndex: 'outstandingAmount', unit: '元', width: 110 },
      { title: '生成节点', dataIndex: 'createNodeName', width: 100 },
      { title: '生成时间', dataIndex: 'createTime', width: 170 },
      { title: '收支方式', dataIndex: 'payTypeName', slotName: 'payType', width: 100 },
      { title: '费用状态', dataIndex: 'feeStatusName', width: 100 },
      { title: '收付款时间', dataIndex: 'payTime', width: 170 },
      { title: '客户名称', dataIndex: 'customerName', width: 100 },
      { title: '确认时间', dataIndex: 'confirmTime', width: 170 },
      { title: '确认人', dataIndex: 'confirmUserName', width: 80 },
      { title: '费用应结时间', dataIndex: 'dueDate', width: 170 },
      { title: '车辆信息', slotName: 'carmsg', width: 240 },
      { title: '违章单号', dataIndex: 'businesCode', width: 240 },
      { title: '关联单号', slotName: 'orderCode', width: 240 },
      { title: '承租人', dataIndex: 'memberName', width: 120 },
      { title: '负责人', slotName: 'undermsg', width: 120 },
      { title: '违章单关联门店', dataIndex: 'siteName', width: 150 },
      { title: '违章时间', slotName: 'time', width: 170 },
      { title: '罚分', dataIndex: 'eventScore', width: 80 },
      { title: '费用备注', dataIndex: 'remark', width: 150 },
      { title: '结算备注', dataIndex: 'settlementRemark', width: 150 },
    ],
    operates: [
      {
        label: '确认收款',
        permission: 'svms:finance:bill:violation.confirm',
        show: (record: any) => record.level == 1 && record.ifCanConfirm == true && record.costType == 0,
        method: (record: any) => {
          feepage.value.show(JSON.stringify([record.id]), record)
        },
      },
      {
        label: '确认付款',
        permission: 'svms:finance:bill:violation.confirm',
        show: (record: any) => record.level == 1 && record.ifCanConfirm == true && record.costType == 1,
        method: (record: any) => {
          feepage.value.show(JSON.stringify([record.id]), record)
        },
      },
      {
        label: '修改费用',
        permission: 'svms:finance:bill:violation.edit',
        show: (record: any) => record.level == 1 && record.canModify == 1,
        method: (record: any) => {
          violationEditFee.value.show(record.id, record)
        },
      },
      {
        label: '收款码',
        permission: 'svms:finance:bill:violation.qrcode',
        show: (record: any) => record.level == 1 && record.feeStatus == 6 && record.payType != 4,
        method: (record: any) => {
          console.log('收款码', record)

          qrcodeFrom.value = 'costCarViolationQRCode'
          qcodeTitle.value = '收款码'
          clickRecord.value = { ...record, bizType: 3, refId: record.businesId }
          payQCodeModal.value = true
        },
      },
      {
        // 取消收款
        label: '取消收款',
        permission: 'svms:finance:bill:violation.qrcodeCancel',
        show: (record: any) => record.level == 1 && record.feeStatus == 6 && record.payType != 4,
        method: (record: any) => {
          console.log('取消收款', record)

          qrcodeFrom.value = 'costCarViolationCancel'
          qcodeTitle.value = '取消收款'
          clickRecord.value = { ...record, bizType: 3, refId: record.businesId }
          payQCodeModal.value = true
        },
      },
    ],
    buttons: [
      {
        mode: 'export',
        permission: 'svms:finance:bill:violation.export',
        label: '导出',
        method: () => handleExport(),
      },
      // {
      //   mode: 'primary',
      //   label: '批量确认',
      //   permission: 'svms:finance:cost:violation.barchConfirm',
      //   method: () => handleBatchConfirm(),
      // },
    ],
  })
  // 导出事件
  const handleExport = () => {
    useExport(violationExportExcel, queryParam)
  }

  const toOrderDetail = (eventType: any, id: any, orderCode: any) => {
    if (eventType == 4) {
      navigateTo(`/short-order/detail/${id}`, `${orderCode}-短租详情`)
    } else if (eventType == 7) {
      navigateTo(`/long-order/detail/${id}`, `${orderCode}-长租详情`)
    }
  }

  const getListFn = (queryParam: any) => {
    return new Promise((resolve) => {
      getViolationFeeList(queryParam).then((res: any) => {
        const result = res.result.data
        const data = tabletolist(result) //表
        tableCompulsory.dataList = data
        tableCompulsory.pagination.pageCount = res.result.total
        resolve({ data, total: res.result.total })
      })
    })
  }

  const getRowClassName = (record: any) => {
    return record.isClass ? 'arco-table-tr-expand' : ''
  }

  const onSearch = () => {
    loadData()
    getStatic()
  }

  /**
   * 1. 当费用状态存在结算中时轮询
   * 2. 当费用状态不存在结算中时，关闭弹窗
   */
  let timer: any = null
  const pollingPayStatus = () => {
    timer = setTimeout(() => {
      getListFn(queryParam).then((res: any) => {
        const payStatus = res.data.every((el: any) => el.feeStatus != 6)
        if (payStatus) {
          clearTimeout(timer)
          timer = null
          payQCodeModal.value = false

          tableCompulsory.dataList = res.data
          tableCompulsory.pagination.pageCount = res.total
          getStatic()
        } else {
          pollingPayStatus()
        }
      })
    }, 3000)
  }

  const loadData = () => {
    queryParam.pageNumber = tableCompulsory.pagination.page || 1
    queryParam.pageSize = tableCompulsory.pagination.pageSize
    tableCompulsory.tableLoading = true
    getListFn(queryParam)
      .then((res: any) => {
        const payStatus = res.data.every((el: any) => el.feeStatus != 6)
        if (!payStatus) {
          pollingPayStatus()
        }
      })
      .finally(() => {
        tableCompulsory.tableLoading = false
      })
  }

  const getStatic = async () => {
    const { result } = await violationFeeMonthCount({})
    nextTick(() => {
      quickSearchData.value[0].value = result.totalAmount || '0'
      quickSearchData.value[1].value = result.feeAmount || '0'
      quickSearchData.value[2].value = result.payAmount || '0'
    })
  }

  // 字段处理
  const tabletolist = (list: any) => {
    list.forEach((el: any) => {
      el.mtype = 'MENU'
      el.level = 1
      if (el.feeDetailList && el.feeDetailList.length) {
        el.children = el.feeDetailList
        el.children.forEach((pl: any) => {
          pl.id = pl.id + 10000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
          pl.mtype = 'TERM1'
          pl.expand = null
          pl.feeName = pl.itemName
          pl.totalAmount = pl.amount
          pl.isClass = true
        })
      } else {
        return false
      }
    })
    return list
  }

  const qcodeConfirm = (details: any) => {
    qcodeCfLoading.value = true

    cancelPay({ id: details.id })
      .then(() => {
        Message.success('取消收款成功')
        payQCodeModal.value = false
      })
      .finally(() => {
        qcodeCfLoading.value = false
      })
  }

  const payQCodeClose = () => {
    tableCompulsory.tableLoading = true
    setTimeout(() => {
      console.log('3s close')
      loadData()
      getStatic()
    }, 3000)
  }

  // 确认成功
  const feepageConfirm = () => {
    console.log('确认成功')
    loadData()
    getStatic()
  }

  const oldIdList = ref([])
  onMounted(() => {
    // 违章关联门店列表
    if (routeQuery.siteIdList) {
      let siteIdList = evalQueryParam(routeQuery.siteIdList)
      // 门店id转换为数组
      const siteIdList2 = siteIdList.map((item) => String(item))
      queryParam.siteIdList = siteIdList2
      nextTick(() => {
        oldIdList.value = siteIdList2
      })
    }
    // 开始结束时间
    if (routeQuery.startTime && routeQuery.endTime) {
      queryParam.dueDate = [routeQuery.startTime, routeQuery.endTime]
      queryParam.dueStartDate = routeQuery.startTime
      queryParam.dueEndDate = routeQuery.endTime
    }
    // 费用状态
    if (routeQuery.feeStatuses) {
      const feeStatuses = evalQueryParam(routeQuery.feeStatuses)
      queryParam.feeStatuses = feeStatuses
    }

    loadData()
    getStatic()
  })
</script>

<style lang="less" scoped>
  .content-item {
    .content-item-name {
      margin-bottom: 4px;
      .staff-can-click {
        color: rgb(var(--primary-6));
        cursor: pointer;
      }
      .tag-pickup {
        padding: 0 3px;
        line-height: 18px;
      }
      :deep(.custom-tag) {
        margin-right: 6px;
        position: relative;
        top: 1px;
      }
    }
    .content-item-tag :deep(.custom-tag.default) {
      line-height: 20px;
      padding: 4px 8px;
    }
  }
  .content-item + .content-item {
    margin-top: 10px;
  }
  .quick-search {
    display: flex;
    margin-bottom: 20px;
  }
  .quick-search-item {
    width: 16%;
    height: 62px;
    padding: 9px 0 9px 16px;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #e5e8ef;
    cursor: pointer;
  }
  .quick-search-item:hover {
    transform: scale(1.1);
    transition: transform 0.3s;
    position: relative;
    z-index: 999;
  }
  .quick-search-item-checked {
    background: #e8f3ff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #1890ff;
  }
  .quick-search-item:nth-of-type(n + 2) {
    margin-left: 20px;
  }
  .quick-search-item-label {
    font-size: 12px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #4e5969;
  }
  .quick-search-item-value {
    font-size: 20px;
    font-family: PingFang SC-Semibold, PingFang SC;
    font-weight: 600;
    color: #1d2129;
  }
  .quick-search-item-value-checked {
    color: #1890ff;
  }
  :deep(.arco-table-expand-btn) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-expand-btn:hover) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  .order-line {
    color: #165dff;
    font-size: 12px;
    text-decoration: underline;
    cursor: pointer;
  }
</style>
